package com.cqeec.waimai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cqeec.waimai.common.R;
import com.cqeec.waimai.entity.User;
import com.cqeec.waimai.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
//        获取手机号
        log.info("发送验证码：手机号为：{}",user.getPhone());
//        生成验证码
        int code = new Random().nextInt(9999);
        if (code < 1000){
            code += 100;
        }
        log.info("验证码为：{}",code);
        session.setAttribute(user.getPhone(),code+"");
        return R.success("验证码发送成功");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info("用户输入的手机号与验证码{}",map);
//        用户输入的手机号与验证码{phone=13579246810,code=337}
//        session     13579246810=337
        String phone = (String) map.get("phone");
//        通过手机号找session中的验证码
        String code = (String) session.getAttribute(phone);
        log.info("session中验证码{}",code);
        if(code!=null && code.equals(map.get("code"))){
//            查询user这个表是不是有这个用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
//            如果没有这个用户就注册一个
            if (user==null){
                user=new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }else {
            return R.error("登陆失败");
        }

    }
}
